package com.ruoyi.loan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.loan.dto.SelectReturnLoanListDto;
import com.ruoyi.loan.entity.LoanRecord;
import com.ruoyi.loan.entity.ReturnLoanRecord;
import com.ruoyi.loan.mapper.LoanRecordMapper;
import com.ruoyi.loan.mapper.ReturnLoanRecordMapper;
import com.ruoyi.loan.service.ReturnLoanService;
import com.ruoyi.loan.vo.ReturnLoanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author lin
 * @Date 2022/4/11 19:03
 */
@Service
public class ReturnLoanServiceImpl extends ServiceImpl<ReturnLoanRecordMapper, ReturnLoanRecord>
        implements ReturnLoanService {

    @Resource
    private ReturnLoanRecordMapper returnLoanRecordMapper;

    @Autowired
    private LoanRecordMapper loanRecordMapper;

    /**
     * 分页获取还款信息
     * @param dto 参数
     * @return 还款信息
     */
    @Override
    public PageInfo getReturnLoanList(SelectReturnLoanListDto dto) {
        //开启分页
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        //获取列表
        List<ReturnLoanVo> returnLoan = returnLoanRecordMapper.getReturnLoan(dto);
        PageInfo pageInfo = new PageInfo(returnLoan);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void repayment(Integer loanId, int money) {
        // 查询数据库判断当前欠款是否已经还清
        LoanRecord loanRecord = loanRecordMapper.selectById(loanId);
        if (loanRecord == null){
            throw new RuntimeException("贷款记录不存在！");
        }
        //剩余贷款金额
        Integer owingAmount = loanRecord.getOwingAmount();
        if (money - owingAmount >0 || money < 0){
            throw new RuntimeException("还款金额不合法");
        }
        // 进行还款
        int owingMoney = owingAmount - money;
        loanRecord.setOwingAmount(owingMoney);
        int result = loanRecordMapper.updateById(loanRecord);
        if (result <1){
            throw new RuntimeException("还款数据更新失败，请重试");
        }
        // 保存还款记录
        ReturnLoanRecord returnLoanRecord = new ReturnLoanRecord();
        returnLoanRecord.setLoanId(loanId);
        returnLoanRecord.setUserId(loanRecord.getUserId());
        returnLoanRecord.setReturnAmount(money);
        int insert = returnLoanRecordMapper.insert(returnLoanRecord);
        if (insert <1){
            throw new RuntimeException("还款记录添加失败，请重试");
        }
    }

    @Override
    public List<ReturnLoanRecord> getLoanReturnRecords(Integer loanId) {
        List<ReturnLoanRecord> recordList = returnLoanRecordMapper.selectList(new QueryWrapper<ReturnLoanRecord>().eq("loan_id", loanId));
        return recordList;
    }
}
